home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 2 / Apprentice-Release2.iso / Source Code / C / Libraries / Berkeley DB 1.6 / hash / hash.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-07-27  |  23.7 KB  |  1,008 lines  |  [TEXT/????]

  1. /*-
  2.  * Copyright (c) 1990, 1993
  3.  *    The Regents of the University of California.  All rights reserved.
  4.  *
  5.  * This code is derived from software contributed to Berkeley by
  6.  * Margo Seltzer.
  7.  *
  8.  * Redistribution and use in source and binary forms, with or without
  9.  * modification, are permitted provided that the following conditions
  10.  * are met:
  11.  * 1. Redistributions of source code must retain the above copyright
  12.  *    notice, this list of conditions and the following disclaimer.
  13.  * 2. Redistributions in binary form must reproduce the above copyright
  14.  *    notice, this list of conditions and the following disclaimer in the
  15.  *    documentation and/or other materials provided with the distribution.
  16.  * 3. All advertising materials mentioning features or use of this software
  17.  *    must display the following acknowledgement:
  18.  *    This product includes software developed by the University of
  19.  *    California, Berkeley and its contributors.
  20.  * 4. Neither the name of the University nor the names of its contributors
  21.  *    may be used to endorse or promote products derived from this software
  22.  *    without specific prior written permission.
  23.  *
  24.  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  25.  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  26.  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  27.  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  28.  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  29.  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  30.  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  31.  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  32.  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  33.  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  34.  * SUCH DAMAGE.
  35.  */
  36.  
  37. #if defined(LIBC_SCCS) && !defined(lint)
  38. static char sccsid[] = "@(#)hash.c    8.1 (Berkeley) 6/6/93";
  39. #endif /* LIBC_SCCS and not lint */
  40.  
  41. #include <sys/param.h>
  42. #include <sys/stat.h>
  43.  
  44. #include <errno.h>
  45. #include <fcntl.h>
  46. #include <stdio.h>
  47. #include <stdlib.h>
  48. #include <string.h>
  49. #include <unistd.h>
  50. #ifdef DEBUG
  51. #include <assert.h>
  52. #endif
  53.  
  54. #ifdef macintosh
  55. #include <sys/fcntl.h>
  56. #include <sys/errno.h>
  57. #endif
  58.  
  59. #include <db.h>
  60. #include "hash.h"
  61. #include "page.h"
  62. #include "extern.h"
  63.  
  64. static int   alloc_segs __P((HTAB *, int));
  65. static int   flush_meta __P((HTAB *));
  66. static int   hash_access __P((HTAB *, ACTION, DBT *, DBT *));
  67. static int   hash_close __P((DB *));
  68. static int   hash_delete __P((const DB *, const DBT *, u_int));
  69. static int   hash_fd __P((const DB *));
  70. static int   hash_get __P((const DB *, const DBT *, DBT *, u_int));
  71. static int   hash_put __P((const DB *, DBT *, const DBT *, u_int));
  72. static void *hash_realloc __P((SEGMENT **, int, int));
  73. static int   hash_seq __P((const DB *, DBT *, DBT *, u_int));
  74. static int   hash_sync __P((const DB *, u_int));
  75. static int   hdestroy __P((HTAB *));
  76. static HTAB *init_hash __P((HTAB *, const char *, HASHINFO *));
  77. static int   init_htab __P((HTAB *, int));
  78. #if BYTE_ORDER == LITTLE_ENDIAN
  79. static void  swap_header __P((HTAB *));
  80. static void  swap_header_copy __P((HASHHDR *, HASHHDR *));
  81. #endif
  82.  
  83. /* Fast arithmetic, relying on powers of 2, */
  84. #define MOD(x, y)        ((x) & ((y) - 1))
  85.  
  86. #define RETURN_ERROR(ERR, LOC)    { save_errno = ERR; goto LOC; }
  87.  
  88. /* Return values */
  89. #define    SUCCESS     (0)
  90. #define    ERROR    (-1)
  91. #define    ABNORMAL (1)
  92.  
  93. #ifdef HASH_STATISTICS
  94. long hash_accesses, hash_collisions, hash_expansions, hash_overflows;
  95. #endif
  96.  
  97. /************************** INTERFACE ROUTINES ***************************/
  98. /* OPEN/CLOSE */
  99.  
  100. extern DB *
  101. __hash_open(file, flags, mode, info)
  102.     const char *file;
  103.     int flags, mode;
  104.     const HASHINFO *info;    /* Special directives for create */
  105. {
  106.     HTAB *hashp;
  107.     struct stat statbuf;
  108.     DB *dbp;
  109.     int bpages, hdrsize, new_table, nsegs, save_errno;
  110.  
  111.     if ((flags & O_ACCMODE) == O_WRONLY) {
  112.         errno = EINVAL;
  113.         return (NULL);
  114.     }
  115.  
  116.     if (!(hashp = calloc(1, sizeof(HTAB))))
  117.         return (NULL);
  118.     hashp->fp = -1;
  119.     /*
  120.      * Select flags relevant to us. Even if user wants write only, we need
  121.      * to be able to read the actual file, so we need to open it read/write.
  122.      * But, the field in the hashp structure needs to be accurate so that
  123.      * we can check accesses.
  124.      */
  125.     hashp->flags = flags = flags & __USE_OPEN_FLAGS;
  126.  
  127.     new_table = 0;
  128.     if (!file || (flags & O_TRUNC) ||
  129.         (stat(file, &statbuf) && (errno == ENOENT))) {
  130.         if (errno == ENOENT)
  131.             errno = 0; /* Just in case someone looks at errno */
  132.         new_table = 1;
  133.     }
  134.     if (file) {
  135. #ifdef macintosh
  136.         if ((hashp->fp = open(file, flags)) == -1)
  137. #else
  138.         if ((hashp->fp = open(file, flags, mode)) == -1)
  139. #endif
  140.             RETURN_ERROR(errno, error0);
  141. #ifndef macintosh
  142.         (void)fcntl(hashp->fp, F_SETFD, 1);
  143. #endif
  144.     }
  145.     if (new_table) {
  146.         if (!(hashp = init_hash(hashp, file, (HASHINFO *)info)))
  147.             RETURN_ERROR(errno, error1);
  148.     } else {
  149.         /* Table already exists */
  150.         if (info && info->hash)
  151.             hashp->hash = info->hash;
  152.         else
  153.             hashp->hash = __default_hash;
  154.  
  155. #ifdef macintosh
  156.         hdrsize = read(hashp->fp, (char *) &hashp->hdr, sizeof(HASHHDR));
  157. #else
  158.         hdrsize = read(hashp->fp, &hashp->hdr, sizeof(HASHHDR));
  159. #endif
  160. #if BYTE_ORDER == LITTLE_ENDIAN
  161.         swap_header(hashp);
  162. #endif
  163.         if (hdrsize == -1)
  164.             RETURN_ERROR(errno, error1);
  165.         if (hdrsize != sizeof(HASHHDR))
  166.             RETURN_ERROR(EFTYPE, error1);
  167.         /* Verify file type, versions and hash function */
  168.         if (hashp->MAGIC != HASHMAGIC)
  169.             RETURN_ERROR(EFTYPE, error1);
  170.         if (hashp->VERSION != HASHVERSION)
  171.             RETURN_ERROR(EFTYPE, error1);
  172.         if (hashp->hash(CHARKEY, sizeof(CHARKEY)) != hashp->H_CHARKEY)
  173.             RETURN_ERROR(EFTYPE, error1);
  174.         /*
  175.          * Figure out how many segments we need.  Max_Bucket is the
  176.          * maximum bucket number, so the number of buckets is
  177.          * max_bucket + 1.
  178.          */
  179.         nsegs = (hashp->MAX_BUCKET + 1 + hashp->SGSIZE - 1) /
  180.              hashp->SGSIZE;
  181.         hashp->nsegs = 0;
  182.         if (alloc_segs(hashp, nsegs))
  183.             /*
  184.              * If alloc_segs fails, table will have been destroyed
  185.              * and errno will have been set.
  186.              */
  187.             return (NULL);
  188.         /* Read in bitmaps */
  189.         bpages = (hashp->SPARES[hashp->OVFL_POINT] +
  190.             (hashp->BSIZE << BYTE_SHIFT) - 1) >>
  191.             (hashp->BSHIFT + BYTE_SHIFT);
  192.  
  193.         hashp->nmaps = bpages;
  194.         (void)memset(&hashp->mapp[0], 0, bpages * sizeof(u_long *));
  195.     }
  196.  
  197.     /* Initialize Buffer Manager */
  198.     if (info && info->cachesize)
  199.         __buf_init(hashp, info->cachesize);
  200.     else
  201.         __buf_init(hashp, DEF_BUFSIZE);
  202.  
  203.     hashp->new_file = new_table;
  204.     hashp->save_file = file && (hashp->flags & O_RDWR);
  205.     hashp->cbucket = -1;
  206.     if (!(dbp = malloc(sizeof(DB)))) {
  207.         save_errno = errno;
  208.         hdestroy(hashp);
  209.         errno = save_errno;
  210.         return (NULL);
  211.     }
  212.     dbp->internal = hashp;
  213.     dbp->close = hash_close;
  214.     dbp->del = hash_delete;
  215.     dbp->fd = hash_fd;
  216.     dbp->get = hash_get;
  217.     dbp->put = hash_put;
  218.     dbp->seq = hash_seq;
  219.     dbp->sync = hash_sync;
  220.     dbp->type = DB_HASH;
  221.  
  222. #ifdef DEBUG
  223.     (void)fprintf(stderr,
  224. "%s\n%s%x\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%x\n%s%x\n%s%d\n%s%d\n",
  225.         "init_htab:",
  226.         "TABLE POINTER   ", hashp,
  227.         "BUCKET SIZE     ", hashp->BSIZE,
  228.         "BUCKET SHIFT    ", hashp->BSHIFT,
  229.         "DIRECTORY SIZE  ", hashp->DSIZE,
  230.         "SEGMENT SIZE    ", hashp->SGSIZE,
  231.         "SEGMENT SHIFT   ", hashp->SSHIFT,
  232.         "FILL FACTOR     ", hashp->FFACTOR,
  233.         "MAX BUCKET      ", hashp->MAX_BUCKET,
  234.         "OVFL POINT         ", hashp->OVFL_POINT,
  235.         "LAST FREED      ", hashp->LAST_FREED,
  236.         "HIGH MASK       ", hashp->HIGH_MASK,
  237.         "LOW  MASK       ", hashp->LOW_MASK,
  238.         "NSEGS           ", hashp->nsegs,
  239.         "NKEYS           ", hashp->NKEYS);
  240. #endif
  241. #ifdef HASH_STATISTICS
  242.     hash_overflows = hash_accesses = hash_collisions = hash_expansions = 0;
  243. #endif
  244.     return (dbp);
  245.  
  246. error1:
  247.     if (hashp != NULL)
  248.         (void)close(hashp->fp);
  249.  
  250. error0:
  251.     free(hashp);
  252.     errno = save_errno;
  253.     return (NULL);
  254. }
  255.  
  256. static int
  257. hash_close(dbp)
  258.     DB *dbp;
  259. {
  260.     HTAB *hashp;
  261.     int retval;
  262.  
  263.     if (!dbp)
  264.         return (ERROR);
  265.  
  266.     hashp = (HTAB *)dbp->internal;
  267.     retval = hdestroy(hashp);
  268.     free(dbp);
  269.     return (retval);
  270. }
  271.  
  272. static int
  273. hash_fd(dbp)
  274.     const DB *dbp;
  275. {
  276.     HTAB *hashp;
  277.  
  278.     if (!dbp)
  279.         return (ERROR);
  280.  
  281.     hashp = (HTAB *)dbp->internal;
  282.     if (hashp->fp == -1) {
  283.         errno = ENOENT;
  284.         return (-1);
  285.     }
  286.     return (hashp->fp);
  287. }
  288.  
  289. /************************** LOCAL CREATION ROUTINES **********************/
  290. static HTAB *
  291. init_hash(hashp, file, info)
  292.     HTAB *hashp;
  293.     const char *file;
  294.     HASHINFO *info;
  295. {
  296.     struct stat statbuf;
  297.     int nelem;
  298.  
  299.     nelem = 1;
  300.     hashp->NKEYS = 0;
  301.     hashp->LORDER = BYTE_ORDER;
  302.     hashp->BSIZE = DEF_BUCKET_SIZE;
  303.     hashp->BSHIFT = DEF_BUCKET_SHIFT;
  304.     hashp->SGSIZE = DEF_SEGSIZE;
  305.     hashp->SSHIFT = DEF_SEGSIZE_SHIFT;
  306.     hashp->DSIZE = DEF_DIRSIZE;
  307.     hashp->FFACTOR = DEF_FFACTOR;
  308.     hashp->hash = __default_hash;
  309.     memset(hashp->SPARES, 0, sizeof(hashp->SPARES));
  310.     memset(hashp->BITMAPS, 0, sizeof (hashp->BITMAPS));
  311.  
  312.     /* Fix bucket size to be optimal for file system */
  313.     if (file != NULL) {
  314.         if (stat(file, &statbuf))
  315.             return (NULL);
  316.         hashp->BSIZE = statbuf.st_blksize;
  317.         hashp->BSHIFT = __log2(hashp->BSIZE);
  318.     }
  319.  
  320.     if (info) {
  321.         if (info->bsize) {
  322.             /* Round pagesize up to power of 2 */
  323.             hashp->BSHIFT = __log2(info->bsize);
  324.             hashp->BSIZE = 1 << hashp->BSHIFT;
  325.             if (hashp->BSIZE > MAX_BSIZE) {
  326.                 errno = EINVAL;
  327.                 return (NULL);
  328.             }
  329.         }
  330.         if (info->ffactor)
  331.             hashp->FFACTOR = info->ffactor;
  332.         if (info->hash)
  333.             hashp->hash = info->hash;
  334.         if (info->nelem)
  335.             nelem = info->nelem;
  336.         if (info->lorder) {
  337.             if (info->lorder != BIG_ENDIAN &&
  338.                 info->lorder != LITTLE_ENDIAN) {
  339.                 errno = EINVAL;
  340.                 return (NULL);
  341.             }
  342.             hashp->LORDER = info->lorder;
  343.         }
  344.     }
  345.     /* init_htab should destroy the table and set errno if it fails */
  346.     if (init_htab(hashp, nelem))
  347.         return (NULL);
  348.     else
  349.         return (hashp);
  350. }
  351. /*
  352.  * This calls alloc_segs which may run out of memory.  Alloc_segs will destroy
  353.  * the table and set errno, so we just pass the error information along.
  354.  *
  355.  * Returns 0 on No Error
  356.  */
  357. static int
  358. init_htab(hashp, nelem)
  359.     HTAB *hashp;
  360.     int nelem;
  361. {
  362.     register int nbuckets, nsegs;
  363.     int l2;
  364.  
  365.     /*
  366.      * Divide number of elements by the fill factor and determine a
  367.      * desired number of buckets.  Allocate space for the next greater
  368.      * power of two number of buckets.
  369.      */
  370.     nelem = (nelem - 1) / hashp->FFACTOR + 1;
  371.  
  372.     l2 = __log2(MAX(nelem, 2));
  373.     nbuckets = 1 << l2;
  374.  
  375.     hashp->SPARES[l2] = l2 + 1;
  376.     hashp->SPARES[l2 + 1] = l2 + 1;
  377.     hashp->OVFL_POINT = l2;
  378.     hashp->LAST_FREED = 2;
  379.  
  380.     /* First bitmap page is at: splitpoint l2 page offset 1 */
  381.     if (__init_bitmap(hashp, OADDR_OF(l2, 1), l2 + 1, 0))
  382.         return (-1);
  383.  
  384.     hashp->MAX_BUCKET = hashp->LOW_MASK = nbuckets - 1;
  385.     hashp->HIGH_MASK = (nbuckets << 1) - 1;
  386.     hashp->HDRPAGES = ((MAX(sizeof(HASHHDR), MINHDRSIZE) - 1) >>
  387.         hashp->BSHIFT) + 1;
  388.  
  389.     nsegs = (nbuckets - 1) / hashp->SGSIZE + 1;
  390.     nsegs = 1 << __log2(nsegs);
  391.  
  392.     if (nsegs > hashp->DSIZE)
  393.         hashp->DSIZE = nsegs;
  394.     return (alloc_segs(hashp, nsegs));
  395. }
  396.  
  397. /********************** DESTROY/CLOSE ROUTINES ************************/
  398.  
  399. /*
  400.  * Flushes any changes to the file if necessary and destroys the hashp
  401.  * structure, freeing all allocated space.
  402.  */
  403. static int
  404. hdestroy(hashp)
  405.     HTAB *hashp;
  406. {
  407.     int i, save_errno;
  408.  
  409.     save_errno = 0;
  410.  
  411. #ifdef HASH_STATISTICS
  412.     (void)fprintf(stderr, "hdestroy: accesses %ld collisions %ld\n",
  413.         hash_accesses, hash_collisions);
  414.     (void)fprintf(stderr, "hdestroy: expansions %ld\n",
  415.         hash_expansions);
  416.     (void)fprintf(stderr, "hdestroy: overflows %ld\n",
  417.         hash_overflows);
  418.     (void)fprintf(stderr, "keys %ld maxp %d segmentcount %d\n",
  419.         hashp->NKEYS, hashp->MAX_BUCKET, hashp->nsegs);
  420.  
  421.     for (i = 0; i < NCACHED; i++)
  422.         (void)fprintf(stderr,
  423.             "spares[%d] = %d\n", i, hashp->SPARES[i]);
  424. #endif
  425.     /*
  426.      * Call on buffer manager to free buffers, and if required,
  427.      * write them to disk.
  428.      */
  429.     if (__buf_free(hashp, 1, hashp->save_file))
  430.         save_errno = errno;
  431.     if (hashp->dir) {
  432.         free(*hashp->dir);    /* Free initial segments */
  433.         /* Free extra segments */
  434.         while (hashp->exsegs--)
  435.             free(hashp->dir[--hashp->nsegs]);
  436.         free(hashp->dir);
  437.     }
  438.     if (flush_meta(hashp) && !save_errno)
  439.         save_errno = errno;
  440.     /* Free Bigmaps */
  441.     for (i = 0; i < hashp->nmaps; i++)
  442.         if (hashp->mapp[i])
  443.             free(hashp->mapp[i]);
  444.  
  445.     if (hashp->fp != -1)
  446.         (void)close(hashp->fp);
  447.  
  448.     if (save_errno) {
  449.         errno = save_errno;
  450.         return (ERROR);
  451.     }
  452.     return (SUCCESS);
  453. }
  454. /*
  455.  * Write modified pages to disk
  456.  *
  457.  * Returns:
  458.  *     0 == OK
  459.  *    -1 ERROR
  460.  */
  461. static int
  462. hash_sync(dbp, flags)
  463.     const DB *dbp;
  464.     u_int flags;
  465. {
  466.     HTAB *hashp;
  467.  
  468.     if (flags != 0) {
  469.         errno = EINVAL;
  470.         return (ERROR);
  471.     }
  472.  
  473.     if (!dbp)
  474.         return (ERROR);
  475.  
  476.     hashp = (HTAB *)dbp->internal;
  477.     if (!hashp->save_file)
  478.         return (0);
  479.     if (__buf_free(hashp, 0, 1) || flush_meta(hashp))
  480.         return (ERROR);
  481.     hashp->new_file = 0;
  482.     return (0);
  483. }
  484.  
  485. /*
  486.  * Returns:
  487.  *     0 == OK
  488.  *    -1 indicates that errno should be set
  489.  */
  490. static int
  491. flush_meta(hashp)
  492.     HTAB *hashp;
  493. {
  494.     HASHHDR *whdrp;
  495. #if BYTE_ORDER == LITTLE_ENDIAN
  496.     HASHHDR whdr;
  497. #endif
  498.     int fp, i, wsize;
  499.  
  500.     if (!hashp->save_file)
  501.         return (0);
  502.     hashp->MAGIC = HASHMAGIC;
  503.     hashp->VERSION = HASHVERSION;
  504.     hashp->H_CHARKEY = hashp->hash(CHARKEY, sizeof(CHARKEY));
  505.  
  506.     fp = hashp->fp;
  507.     whdrp = &hashp->hdr;
  508. #if BYTE_ORDER == LITTLE_ENDIAN
  509.     whdrp = &whdr;
  510.     swap_header_copy(&hashp->hdr, whdrp);
  511. #endif
  512.     if ((lseek(fp, (off_t)0, SEEK_SET) == -1) ||
  513. #ifdef macintosh
  514.         ((wsize = write(fp, (char *) whdrp, sizeof(HASHHDR))) == -1))
  515. #else
  516.         ((wsize = write(fp, whdrp, sizeof(HASHHDR))) == -1))
  517. #endif
  518.         return (-1);
  519.     else
  520.         if (wsize != sizeof(HASHHDR)) {
  521.             errno = EFTYPE;
  522.             hashp->errno = errno;
  523.             return (-1);
  524.         }
  525.     for (i = 0; i < NCACHED; i++)
  526.         if (hashp->mapp[i])
  527.             if (__put_page(hashp, (char *)hashp->mapp[i],
  528.                 hashp->BITMAPS[i], 0, 1))
  529.                 return (-1);
  530.     return (0);
  531. }
  532.  
  533. /*******************************SEARCH ROUTINES *****************************/
  534. /*
  535.  * All the access routines return
  536.  *
  537.  * Returns:
  538.  *     0 on SUCCESS
  539.  *     1 to indicate an external ERROR (i.e. key not found, etc)
  540.  *    -1 to indicate an internal ERROR (i.e. out of memory, etc)
  541.  */
  542. static int
  543. hash_get(dbp, key, data, flag)
  544.     const DB *dbp;
  545.     const DBT *key;
  546.     DBT *data;
  547.     u_int flag;
  548. {
  549.     HTAB *hashp;
  550.  
  551.     hashp = (HTAB *)dbp->internal;
  552.     if (flag) {
  553.         hashp->errno = errno = EINVAL;
  554.         return (ERROR);
  555.     }
  556.     return (hash_access(hashp, HASH_GET, (DBT *)key, data));
  557. }
  558.  
  559. static int
  560. hash_put(dbp, key, data, flag)
  561.     const DB *dbp;
  562.     DBT *key;
  563.     const DBT *data;
  564.     u_int flag;
  565. {
  566.     HTAB *hashp;
  567.  
  568.     hashp = (HTAB *)dbp->internal;
  569.     if (flag && flag != R_NOOVERWRITE) {
  570.         hashp->errno = errno = EINVAL;
  571.         return (ERROR);
  572.     }
  573.     if ((hashp->flags & O_ACCMODE) == O_RDONLY) {
  574.         hashp->errno = errno = EPERM;
  575.         return (ERROR);
  576.     }
  577.     return (hash_access(hashp, flag == R_NOOVERWRITE ?
  578.         HASH_PUTNEW : HASH_PUT, (DBT *)key, (DBT *)data));
  579. }
  580.  
  581. static int
  582. hash_delete(dbp, key, flag)
  583.     const DB *dbp;
  584.     const DBT *key;
  585.     u_int flag;        /* Ignored */
  586. {
  587.     HTAB *hashp;
  588.  
  589.     hashp = (HTAB *)dbp->internal;
  590.     if (flag && flag != R_CURSOR) {
  591.         hashp->errno = errno = EINVAL;
  592.         return (ERROR);
  593.     }
  594.     if ((hashp->flags & O_ACCMODE) == O_RDONLY) {
  595.         hashp->errno = errno = EPERM;
  596.         return (ERROR);
  597.     }
  598.     return (hash_access(hashp, HASH_DELETE, (DBT *)key, NULL));
  599. }
  600.  
  601. /*
  602.  * Assume that hashp has been set in wrapper routine.
  603.  */
  604. static int
  605. hash_access(hashp, action, key, val)
  606.     HTAB *hashp;
  607.     ACTION action;
  608.     DBT *key, *val;
  609. {
  610.     register BUFHEAD *rbufp;
  611.     BUFHEAD *bufp, *save_bufp;
  612.     register u_short *bp;
  613.     register int n, ndx, off, size;
  614.     register char *kp;
  615.     u_short pageno;
  616.  
  617. #ifdef HASH_STATISTICS
  618.     hash_accesses++;
  619. #endif
  620.  
  621.     off = hashp->BSIZE;
  622.     size = key->size;
  623.     kp = (char *)key->data;
  624.     rbufp = __get_buf(hashp, __call_hash(hashp, kp, size), NULL, 0);
  625.     if (!rbufp)
  626.         return (ERROR);
  627.     save_bufp = rbufp;
  628.  
  629.     /* Pin the bucket chain */
  630.     rbufp->flags |= BUF_PIN;
  631.     for (bp = (u_short *)rbufp->page, n = *bp++, ndx = 1; ndx < n;)
  632.         if (bp[1] >= REAL_KEY) {
  633.             /* Real key/data pair */
  634.             if (size == off - *bp &&
  635.                 memcmp(kp, rbufp->page + *bp, size) == 0)
  636.                 goto found;
  637.             off = bp[1];
  638. #ifdef HASH_STATISTICS
  639.             hash_collisions++;
  640. #endif
  641.             bp += 2;
  642.             ndx += 2;
  643.         } else if (bp[1] == OVFLPAGE) {
  644.             rbufp = __get_buf(hashp, *bp, rbufp, 0);
  645.             if (!rbufp) {
  646.                 save_bufp->flags &= ~BUF_PIN;
  647.                 return (ERROR);
  648.             }
  649.             /* FOR LOOP INIT */
  650.             bp = (u_short *)rbufp->page;
  651.             n = *bp++;
  652.             ndx = 1;
  653.             off = hashp->BSIZE;
  654.         } else if (bp[1] < REAL_KEY) {
  655.             if ((ndx =
  656.                 __find_bigpair(hashp, rbufp, ndx, kp, size)) > 0)
  657.                 goto found;
  658.             if (ndx == -2) {
  659.                 bufp = rbufp;
  660.                 if (!(pageno =
  661.                     __find_last_page(hashp, &bufp))) {
  662.                     ndx = 0;
  663.                     rbufp = bufp;
  664.                     break;    /* FOR */
  665.                 }
  666.                 rbufp = __get_buf(hashp, pageno, bufp, 0);
  667.                 if (!rbufp) {
  668.                     save_bufp->flags &= ~BUF_PIN;
  669.                     return (ERROR);
  670.                 }
  671.                 /* FOR LOOP INIT */
  672.                 bp = (u_short *)rbufp->page;
  673.                 n = *bp++;
  674.                 ndx = 1;
  675.                 off = hashp->BSIZE;
  676.             } else {
  677.                 save_bufp->flags &= ~BUF_PIN;
  678.                 return (ERROR);
  679.             }
  680.         }
  681.  
  682.     /* Not found */
  683.     switch (action) {
  684.     case HASH_PUT:
  685.     case HASH_PUTNEW:
  686.         if (__addel(hashp, rbufp, key, val)) {
  687.             save_bufp->flags &= ~BUF_PIN;
  688.             return (ERROR);
  689.         } else {
  690.             save_bufp->flags &= ~BUF_PIN;
  691.             return (SUCCESS);
  692.         }
  693.     case HASH_GET:
  694.     case HASH_DELETE:
  695.     default:
  696.         save_bufp->flags &= ~BUF_PIN;
  697.         return (ABNORMAL);
  698.     }
  699.  
  700. found:
  701.     switch (action) {
  702.     case HASH_PUTNEW:
  703.         save_bufp->flags &= ~BUF_PIN;
  704.         return (ABNORMAL);
  705.     case HASH_GET:
  706.         bp = (u_short *)rbufp->page;
  707.         if (bp[ndx + 1] < REAL_KEY) {
  708.             if (__big_return(hashp, rbufp, ndx, val, 0))
  709.                 return (ERROR);
  710.         } else {
  711.             val->data = (u_char *)rbufp->page + (int)bp[ndx + 1];
  712.             val->size = bp[ndx] - bp[ndx + 1];
  713.         }
  714.         break;
  715.     case HASH_PUT:
  716.         if ((__delpair(hashp, rbufp, ndx)) ||
  717.             (__addel(hashp, rbufp, key, val))) {
  718.             save_bufp->flags &= ~BUF_PIN;
  719.             return (ERROR);
  720.         }
  721.         break;
  722.     case HASH_DELETE:
  723.         if (__delpair(hashp, rbufp, ndx))
  724.             return (ERROR);
  725.         break;
  726.     default:
  727.         abort();
  728.     }
  729.     save_bufp->flags &= ~BUF_PIN;
  730.     return (SUCCESS);
  731. }
  732.  
  733. static int
  734. hash_seq(dbp, key, data, flag)
  735.     const DB *dbp;
  736.     DBT *key, *data;
  737.     u_int flag;
  738. {
  739.     register u_int bucket;
  740.     register BUFHEAD *bufp;
  741.     HTAB *hashp;
  742.     u_short *bp, ndx;
  743.  
  744.     hashp = (HTAB *)dbp->internal;
  745.     if (flag && flag != R_FIRST && flag != R_NEXT) {
  746.         hashp->errno = errno = EINVAL;
  747.         return (ERROR);
  748.     }
  749. #ifdef HASH_STATISTICS
  750.     hash_accesses++;
  751. #endif
  752.     if ((hashp->cbucket < 0) || (flag == R_FIRST)) {
  753.         hashp->cbucket = 0;
  754.         hashp->cndx = 1;
  755.         hashp->cpage = NULL;
  756.     }
  757.  
  758.     for (bp = NULL; !bp || !bp[0]; ) {
  759.         if (!(bufp = hashp->cpage)) {
  760.             for (bucket = hashp->cbucket;
  761.                 bucket <= hashp->MAX_BUCKET;
  762.                 bucket++, hashp->cndx = 1) {
  763.                 bufp = __get_buf(hashp, bucket, NULL, 0);
  764.                 if (!bufp)
  765.                     return (ERROR);
  766.                 hashp->cpage = bufp;
  767.                 bp = (u_short *)bufp->page;
  768.                 if (bp[0])
  769.                     break;
  770.             }
  771.             hashp->cbucket = bucket;
  772.             if (hashp->cbucket > hashp->MAX_BUCKET) {
  773.                 hashp->cbucket = -1;
  774.                 return (ABNORMAL);
  775.             }
  776.         } else
  777.             bp = (u_short *)hashp->cpage->page;
  778.  
  779. #ifdef DEBUG
  780.         assert(bp);
  781.         assert(bufp);
  782. #endif
  783.         while (bp[hashp->cndx + 1] == OVFLPAGE) {
  784.             bufp = hashp->cpage =
  785.                 __get_buf(hashp, bp[hashp->cndx], bufp, 0);
  786.             if (!bufp)
  787.                 return (ERROR);
  788.             bp = (u_short *)(bufp->page);
  789.             hashp->cndx = 1;
  790.         }
  791.         if (!bp[0]) {
  792.             hashp->cpage = NULL;
  793.             ++hashp->cbucket;
  794.         }
  795.     }
  796.     ndx = hashp->cndx;
  797.     if (bp[ndx + 1] < REAL_KEY) {
  798.         if (__big_keydata(hashp, bufp, key, data, 1))
  799.             return (ERROR);
  800.     } else {
  801.         key->data = (u_char *)hashp->cpage->page + bp[ndx];
  802.         key->size = (ndx > 1 ? bp[ndx - 1] : hashp->BSIZE) - bp[ndx];
  803.         data->data = (u_char *)hashp->cpage->page + bp[ndx + 1];
  804.         data->size = bp[ndx] - bp[ndx + 1];
  805.         ndx += 2;
  806.         if (ndx > bp[0]) {
  807.             hashp->cpage = NULL;
  808.             hashp->cbucket++;
  809.             hashp->cndx = 1;
  810.         } else
  811.             hashp->cndx = ndx;
  812.     }
  813.     return (SUCCESS);
  814. }
  815.  
  816. /********************************* UTILITIES ************************/
  817.  
  818. /*
  819.  * Returns:
  820.  *     0 ==> OK
  821.  *    -1 ==> Error
  822.  */
  823. extern int
  824. __expand_table(hashp)
  825.     HTAB *hashp;
  826. {
  827.     u_int old_bucket, new_bucket;
  828.     int dirsize, new_segnum, spare_ndx;
  829.  
  830. #ifdef HASH_STATISTICS
  831.     hash_expansions++;
  832. #endif
  833.     new_bucket = ++hashp->MAX_BUCKET;
  834.     old_bucket = (hashp->MAX_BUCKET & hashp->LOW_MASK);
  835.  
  836.     new_segnum = new_bucket >> hashp->SSHIFT;
  837.  
  838.     /* Check if we need a new segment */
  839.     if (new_segnum >= hashp->nsegs) {
  840.         /* Check if we need to expand directory */
  841.         if (new_segnum >= hashp->DSIZE) {
  842.             /* Reallocate directory */
  843.             dirsize = hashp->DSIZE * sizeof(SEGMENT *);
  844.             if (!hash_realloc(&hashp->dir, dirsize, dirsize << 1))
  845.                 return (-1);
  846.             hashp->DSIZE = dirsize << 1;
  847.         }
  848.         if (!(hashp->dir[new_segnum] =
  849.             calloc(hashp->SGSIZE, sizeof(SEGMENT))))
  850.             return (-1);
  851.         hashp->exsegs++;
  852.         hashp->nsegs++;
  853.     }
  854.     /*
  855.      * If the split point is increasing (MAX_BUCKET's log base 2
  856.      * * increases), we need to copy the current contents of the spare
  857.      * split bucket to the next bucket.
  858.      */
  859.     spare_ndx = __log2(hashp->MAX_BUCKET + 1);
  860.     if (spare_ndx > hashp->OVFL_POINT) {
  861.         hashp->SPARES[spare_ndx] = hashp->SPARES[hashp->OVFL_POINT];
  862.         hashp->OVFL_POINT = spare_ndx;
  863.     }
  864.  
  865.     if (new_bucket > hashp->HIGH_MASK) {
  866.         /* Starting a new doubling */
  867.         hashp->LOW_MASK = hashp->HIGH_MASK;
  868.         hashp->HIGH_MASK = new_bucket | hashp->LOW_MASK;
  869.     }
  870.     /* Relocate records to the new bucket */
  871.     return (__split_page(hashp, old_bucket, new_bucket));
  872. }
  873.  
  874. /*
  875.  * If realloc guarantees that the pointer is not destroyed if the realloc
  876.  * fails, then this routine can go away.
  877.  */
  878. static void *
  879. hash_realloc(p_ptr, oldsize, newsize)
  880.     SEGMENT **p_ptr;
  881.     int oldsize, newsize;
  882. {
  883.     register void *p;
  884.  
  885.     if (p = malloc(newsize)) {
  886.         memmove(p, *p_ptr, oldsize);
  887.         memset((char *) p + oldsize, 0, newsize - oldsize);
  888.         free(*p_ptr);
  889.         *p_ptr = p;
  890.     }
  891.     return (p);
  892. }
  893.  
  894. extern u_int
  895. __call_hash(hashp, k, len)
  896.     HTAB *hashp;
  897.     char *k;
  898.     int len;
  899. {
  900.     int n, bucket;
  901.  
  902.     n = hashp->hash(k, len);
  903.     bucket = n & hashp->HIGH_MASK;
  904.     if (bucket > hashp->MAX_BUCKET)
  905.         bucket = bucket & hashp->LOW_MASK;
  906.     return (bucket);
  907. }
  908.  
  909. /*
  910.  * Allocate segment table.  On error, destroy the table and set errno.
  911.  *
  912.  * Returns 0 on success
  913.  */
  914. static int
  915. alloc_segs(hashp, nsegs)
  916.     HTAB *hashp;
  917.     int nsegs;
  918. {
  919.     register int i;
  920.     register SEGMENT store;
  921.  
  922.     int save_errno;
  923.  
  924.     if (!(hashp->dir = calloc(hashp->DSIZE, sizeof(SEGMENT *)))) {
  925.         save_errno = errno;
  926.         (void)hdestroy(hashp);
  927.         errno = save_errno;
  928.         return (-1);
  929.     }
  930.     /* Allocate segments */
  931.     store = calloc(nsegs << hashp->SSHIFT, sizeof(SEGMENT));
  932.     if (!store) {
  933.         save_errno = errno;
  934.         (void)hdestroy(hashp);
  935.         errno = save_errno;
  936.         return (-1);
  937.     }
  938.     for (i = 0; i < nsegs; i++, hashp->nsegs++)
  939.         hashp->dir[i] = &store[i << hashp->SSHIFT];
  940.     return (0);
  941. }
  942.  
  943. #if BYTE_ORDER == LITTLE_ENDIAN
  944. /*
  945.  * Hashp->hdr needs to be byteswapped.
  946.  */
  947. static void
  948. swap_header_copy(srcp, destp)
  949.     HASHHDR *srcp, *destp;
  950. {
  951.     int i;
  952.  
  953.     BLSWAP_COPY(srcp->magic, destp->magic);
  954.     BLSWAP_COPY(srcp->version, destp->version);
  955.     BLSWAP_COPY(srcp->lorder, destp->lorder);
  956.     BLSWAP_COPY(srcp->bsize, destp->bsize);
  957.     BLSWAP_COPY(srcp->bshift, destp->bshift);
  958.     BLSWAP_COPY(srcp->dsize, destp->dsize);
  959.     BLSWAP_COPY(srcp->ssize, destp->ssize);
  960.     BLSWAP_COPY(srcp->sshift, destp->sshift);
  961.     BLSWAP_COPY(srcp->ovfl_point, destp->ovfl_point);
  962.     BLSWAP_COPY(srcp->last_freed, destp->last_freed);
  963.     BLSWAP_COPY(srcp->max_bucket, destp->max_bucket);
  964.     BLSWAP_COPY(srcp->high_mask, destp->high_mask);
  965.     BLSWAP_COPY(srcp->low_mask, destp->low_mask);
  966.     BLSWAP_COPY(srcp->ffactor, destp->ffactor);
  967.     BLSWAP_COPY(srcp->nkeys, destp->nkeys);
  968.     BLSWAP_COPY(srcp->hdrpages, destp->hdrpages);
  969.     BLSWAP_COPY(srcp->h_charkey, destp->h_charkey);
  970.     for (i = 0; i < NCACHED; i++) {
  971.         BLSWAP_COPY(srcp->spares[i], destp->spares[i]);
  972.         BSSWAP_COPY(srcp->bitmaps[i], destp->bitmaps[i]);
  973.     }
  974. }
  975.  
  976. static void
  977. swap_header(hashp)
  978.     HTAB *hashp;
  979. {
  980.     HASHHDR *hdrp;
  981.     int i;
  982.  
  983.     hdrp = &hashp->hdr;
  984.  
  985.     BLSWAP(hdrp->magic);
  986.     BLSWAP(hdrp->version);
  987.     BLSWAP(hdrp->lorder);
  988.     BLSWAP(hdrp->bsize);
  989.     BLSWAP(hdrp->bshift);
  990.     BLSWAP(hdrp->dsize);
  991.     BLSWAP(hdrp->ssize);
  992.     BLSWAP(hdrp->sshift);
  993.     BLSWAP(hdrp->ovfl_point);
  994.     BLSWAP(hdrp->last_freed);
  995.     BLSWAP(hdrp->max_bucket);
  996.     BLSWAP(hdrp->high_mask);
  997.     BLSWAP(hdrp->low_mask);
  998.     BLSWAP(hdrp->ffactor);
  999.     BLSWAP(hdrp->nkeys);
  1000.     BLSWAP(hdrp->hdrpages);
  1001.     BLSWAP(hdrp->h_charkey);
  1002.     for (i = 0; i < NCACHED; i++) {
  1003.         BLSWAP(hdrp->spares[i]);
  1004.         BSSWAP(hdrp->bitmaps[i]);
  1005.     }
  1006. }
  1007. #endif
  1008.